<template>
  <div>
    <div class="title">
      <label>{{ title }}</label>
      <label @click="onAdd">
        <a-icon type="plus-square" theme="twoTone" />
      </label>
    </div>
    <slot></slot>
    <a-table
      style="margin-top: 0.5rem"
      bordered
      :columns="columnsfull"
      :dataSource="dataSource"
      :scroll="scrollCal"
      :pagination="pagination"
    >
      <span slot="action" slot-scope="record">
        <a @click="onDetail(record)">详情</a>
        <a-divider type="vertical" />
        <a @click="onEdit(record)">编辑</a>
        <a-divider type="vertical" />
        <a-popconfirm
          v-if="dataSource.length"
          title="确定删除?"
          @confirm="() => onDelete(record)"
        >
          <a href="javascript:;">删除</a>
        </a-popconfirm>
        <!--        <a @click="handledel()">删除</a>-->
      </span>
    </a-table>
  </div>
</template>

<script>
export default {
  name: "SqlTable",
  data() {
    return {};
  },
  props: {
    title: String,
    columns: Array,
    dataSource: Array,
    pagination: { total: 20 }
  },
  created() {
    console.log("123");
  },
  computed: {
    //定义完整的表头
    columnsfull() {
      var obj = [];
      obj = JSON.parse(JSON.stringify(this.columns)); //this.templateData是父组件传递的对象
      obj.push({
        title: "操作",
        key: "operation",
        fixed: "right",
        width: 160,
        scopedSlots: { customRender: "action" }
      });
      return obj;
    },
    scrollCal() {
      const y = document.documentElement.clientHeight - 380;
      var x = this.columns.reduce(function(prev, cur) {
        return prev + cur.width;
      });

      return {
        x: x + 160,
        y: y
      };
    }
  },
  methods: {
    //点击添加图标
    onAdd() {
      this.$emit("handleAdd");
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource];
      const target = dataSource.find(item => item.key === key);
      if (target) {
        target[dataIndex] = value;
        this.dataSource = dataSource;
      }
    },
    onDelete(record) {
      //点击删除按钮
      this.$emit("handleDelete", record);
      // const dataSource = [...this.dataSource];
      // this.dataSource = dataSource.filter(item => item.key !== key);
    },
    onEdit(record) {
      //点击编辑按钮
      this.$emit("handleEdit", record);
    },
    onDetail(record) {
      //点击详情按钮
      this.$emit("handleDetail", record);
    }
  }
};
</script>

<style scoped="scoped">
.title {
  font-size: 1.5rem;
  margin-bottom: 0.5rem;
}

.anticon {
  float: right;
  margin-right: 50px;
  font-size: 24px;
}
</style>
